package com.bite.java_chatroom.mapper;

import com.bite.java_chatroom.model.MessageSession;
import com.bite.java_chatroom.model.UserInfo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface MessageSessionMapper {
    //通过用户id查会话id，并按时间降序排序
    @Select("select session_id from message_session where session_id in" +
            "(select id from message_session_user where user_id = #{id}) order by last_time desc")
    List<Integer> getSessionList(Integer id);

    //在统一会话中查friend
    @Select("select id,username from user_info where id in" +
            "(select user_id from message_session_user where id = #{sessionId} and user_id != #{userSelfId})")
    List<UserInfo> getFriendBySessionId(Integer sessionId,Integer userSelfId);

    @Select("select id,username from user_info where id in" +
            "(select user_id from message_session_user where id = #{sessionId})")
    List<UserInfo> getFriendsBySessionId(Integer sessionId);

    //添加会话
    @Options(useGeneratedKeys = true, keyProperty = "sessionId", keyColumn = "session_id")
    @Insert("insert into message_session values ()")
    Integer addSession(MessageSession session);

    //添加会话与用户的关系表
    @Insert("insert into message_session_user values (#{sessionId},#{userId}) ")
    Integer addMessageSessionUser(Integer sessionId,Integer userId);

    @Select("select id from message_session_user where user_id = #{friendId} and id in " +
            "(select id from message_session_user where user_id = #{userId})")
    Integer getSessionIdByfriendId(Integer userId, Integer friendId);
}
